package com.emotion.sshticket.mail;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailUtil {
	private static Properties propertySource;

	public void setProperty(Properties propertySource) {
		MailUtil.propertySource = propertySource;
	}

	public static void sendMail(String receiveAddr, String fileName, Map<String, Object> dataMap) throws Exception {
		Properties properties = System.getProperties();
		String mailHost = propertySource.getProperty("mail.SMTP_HOST_NAME");
		String mailport = propertySource.getProperty("mail.SMTP.PORT");
		String authId = propertySource.getProperty("mail.authId");
		String authPw = propertySource.getProperty("mail.authPwd");
		String fromAddr = propertySource.getProperty("mail.fromAddr");

		properties.put("mail.smtp.host", mailHost);
		properties.put("mail.smtp.starttls.enable", "true");
		properties.put("mail.smtp.port", mailport);
		properties.put("mail.smtp.auth", "true");

		EmailAuthenticator authenticator = new EmailAuthenticator(authId, authPw);
		Session session = Session.getDefaultInstance(properties, authenticator);

		try{
			MimeMessage mail = new MimeMessage(session);
			mail.setFrom(new InternetAddress(fromAddr));
			mail.addRecipient(Message.RecipientType.TO, new InternetAddress(receiveAddr));

			Map<String, Object> bodyMap = getMailText(fileName, dataMap);
			String subject = (String) bodyMap.get("subject");
			String body = (String) bodyMap.get("body");

	        mail.setSubject(subject, "ISO-2022-JP");
	        mail.setText(body,"ISO-2022-JP");

			Transport.send(mail);
		} catch (MessagingException mex) {
			mex.printStackTrace();
		}
	}

	public static Map<String, Object> getMailText(String fileName, Map<String, Object> dataMap) throws Exception {
		String body = "";
		String subject = "";

		String rootPath = propertySource.getProperty("mail.SERVER_ROOT_DIR");
		String folderPath = propertySource.getProperty("mail.mailForm_dir");
		String filePath = rootPath + folderPath + fileName;
		File file = new File(filePath);
	    if ((!(file.exists())) || (file == null)) {
	    	throw new Exception("check filePath==>" + filePath);
	    }

	    FileInputStream fs = null;
	    InputStreamReader in = null;
	    BufferedReader br = null;
	    StringBuffer sb = null;
	    Map<String, Object> resultMap = null;
	    try {
	    	String temp;
	    	fs = new FileInputStream(filePath);
	    	in = new InputStreamReader(fs, "UTF-8");
	    	br = new BufferedReader(in);
	    	sb = new StringBuffer();

	    	int index = 0;
	    	while ((temp = br.readLine()) != null) {
	    		if (index == 0) {
	    			if (subject == null || subject.equals("")) {
	    				subject = temp;
	    			}
	    			++index;
	    		} else {
	    			sb.append(temp + "\r\n");
	    		}
	    	}

	    	body = sb.toString();

	    	if (dataMap != null) {
	    		Iterator<String> iterator = dataMap.keySet().iterator();
	    		while (iterator.hasNext()) {
	    			String key = iterator.next();
	    			String replaceKey = "#<" + key + ">";
	    			if (key != null) {
	    				if (dataMap.get(key) == null) {
	    					body = body.replaceAll(replaceKey, "");
	    					subject = subject.replaceAll(replaceKey, "");
	    				} else {
	    					String value = String.valueOf(dataMap.get(key));
	    					body = body.replaceAll(replaceKey, value);
	    					subject = subject.replaceAll(replaceKey, value);
	    				}
	    			}
	    		}
	    		body = body.replaceAll("#<[^>]*>", "");
	    	}
	    	resultMap = new HashMap<String, Object>();
	    	resultMap.put("body", body);
	    	resultMap.put("subject", subject);
    	} catch (Exception e) {
	    	e.printStackTrace();
		} finally {
			try { fs.close(); } catch (IOException localIOException1) { }
			try { in.close(); } catch (IOException localIOException2) { }
			try { br.close(); } catch (IOException localIOException3) { }
		}
	    return resultMap;
	}
}
